package com.sparrow.servicemgr.consul;


import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.health.model.HealthService;
import com.google.common.base.Preconditions;
import com.sparrow.common.util.PropertiesUtil;
import java.util.List;

/**
 * Consul服务注册与发现
 *
 * IT 圈念 “康索尔”
 */
public class ConsulManager {


    private final ConsulClient consulClient;

    public ConsulManager() {
        String url = PropertiesUtil.getProperty("consul.agent.url");
        Preconditions.checkNotNull(url, "consul.agent.url 配置未填写");
        consulClient = new ConsulClient(url);
    }
    /**
     * 注册服务
     * @param name 服务名
     * @param id 服务唯一id
     * @param address 地址
     * @param port 端口
     */
    public void register(String name, String id, String address, int port) {
        NewService newService = new NewService();
        newService.setId(id);          // 服务唯一ID
        newService.setName(name);           // 服务名
        newService.setAddress(address);         // 服务地址
        newService.setPort(port);

        //服务检查 consul agent 会定期发起请求检查服务是否健康
        //url=http://10.97.50.246:8081/?packetId=201
        String healthUrl = PropertiesUtil.getProperty("consul.health.url");
        Preconditions.checkNotNull(healthUrl, "consul.health.url 配置未填写");
        NewService.Check serviceCheck = new NewService.Check();
        serviceCheck.setHttp(healthUrl);
        serviceCheck.setInterval("10s");
        newService.setCheck(serviceCheck);

        consulClient.agentServiceRegister(newService);
    }

    public void deregister(String serviceId) {
        consulClient.agentServiceDeregister(serviceId);
    }

    /**
     * 获得健康的服务列表
     * @param name
     * @return
     */
    public List<HealthService> getHealthServices(String name) {
        Response<List<HealthService>> healthyServices = consulClient.getHealthServices(
                name, true, null);
        return healthyServices.getValue();
    }

    /**
     * 通过服务名和ID查询唯一健康服务实例
     * @param name 服务名
     * @param id 服务唯一ID
     * @return 匹配的 HealthService，如果不存在则返回 null
     */
    public HealthService getHealthServiceByNameAndId(String name, String id) {
        List<HealthService> services = getHealthServices(name);
        for (HealthService service : services) {
            if (service.getService().getId().equals(id)) {
                return service;
            }
        }
        return null;
    }

}
